package com.goods.link.hai360;

import com.goods.link.DemoDriver;
import com.goods.link.LinkProduct;
import com.thoughtworks.selenium.Wait;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.util.concurrent.TimeUnit;

/**
 * Created by zhengjunbo on 2015/9/14.
 */
public class Hai360 {
    public LinkProduct getLinkProduct(final RemoteWebDriver driver,final String requestUrl){
        LinkProduct linkProduct = new LinkProduct();

        driver.get("http://www.hai360.com/");
        driver.findElementByCssSelector("#search-form > input.txt-search").sendKeys(requestUrl);
        driver.findElementByCssSelector("#search-form > input.btn-search").click();
        final String currentUrl = driver.getCurrentUrl();
        new Wait() {
            @Override
            public boolean until() {
                System.out.println(driver.getCurrentUrl());
                if(currentUrl.equals(driver.getCurrentUrl())){
                    try2Click(driver, By.cssSelector("#search-form > input.btn-search"));

                    return false;
                }
                return true;
            }
        }.wait("等待点击超时", 30000L,3000L);
        linkProduct.setUrl(driver.getCurrentUrl());
        String price = driver.findElementByCssSelector("body > div.container > div.metadata > div.property > dl.prop-item.prop-price > dd > span.price").getText();
        linkProduct.setPrice(price.substring(1));
        String shipPrice = driver.findElementByCssSelector("body > div.container > div.metadata > div.property > dl.prop-item.prop-freight > dd").getText();
        linkProduct.setShipPrice(shipPrice.substring(1,shipPrice.indexOf(" (")));

        return linkProduct;
    }

    private void try2Click(RemoteWebDriver driver,By by) {
        driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);

        try {
            driver.findElement(by).click();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        }
    }
}
